/**
 * This file is part of RailEGo
 * Copyright (c) 2023 Guo Tingjin <dev@peercat.cn>
 * RailEGo is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * RailEGo is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program. If not, see <https://www.gnu.org/licenses/>.
 */
import formInfo from '@ohos.app.form.formInfo';
import formBindingData from '@ohos.app.form.formBindingData';
import FormExtensionAbility from '@ohos.app.form.FormExtensionAbility';
import { ApiMan, CookieMan, StringUtils } from '@libs/common';
import formProvider from '@ohos.app.form.formProvider';
import promptAction from '@ohos.promptAction';

export default class CardAbility2x2 extends FormExtensionAbility {
  refreshForm(formId) {
    CookieMan.getInstance(this.context).setFromCache();
    var raw = CookieMan.getInstance(this.context).get('activeTicketInfo');
    if (raw == false)
      return;
    const o = JSON.parse(raw);
    for (var i = 0; i < o.tickets.length; i++) {
      const depart = (new Date(o.tickets[i].start_train_date_page)).getTime();
      var timeLeft = '';
      if (depart > new Date().getTime()) {
        const t = new Date(depart - (new Date()).getTime());
        if (t.getDate() > 1) {
          timeLeft = `${t.getDate()}天`;
        } else if (t.getHours() > 6) {
          timeLeft = StringUtils.formatDateByObj(t, "H小时");
        } else {
          timeLeft = StringUtils.formatDateByObj(t, "H小时M分钟");
        }
        var info = {
          'departTime': timeLeft,
          'departStation': `${o.tickets[i].stationTrainDTO.from_station_name}站`,
          'trainCode': `${o.tickets[i].stationTrainDTO.station_train_code}`,
          'stationStr': `${o.tickets[i].stationTrainDTO.to_station_name}站`,
          'coachStr': `${o.tickets[i].coach_name}车`,
          'seatStr': `${o.tickets[i].seat_name}座`,
          'ticketCheck': `加载中`
        };
        var formInfo = formBindingData.createFormBindingData(info);
        formProvider.updateForm(formId, formInfo);
        ApiMan.getInstance().requestTicketCheck({
          trainDate: o.tickets[i].start_train_date_page.split(' ')[0],
          stationTrainCode: o.tickets[i].stationTrainDTO.station_train_code,
          fromStationTelecode: o.tickets[i].stationTrainDTO.from_station_telecode
        })
          .then(response => {
            var info = {
              'ticketCheck': `${response.result ? response.trainPlatform.replace('检票口', '') : '暂无数据'}`
            };
            var formInfo = formBindingData.createFormBindingData(info);
            formProvider.updateForm(formId, formInfo);
          })
          .catch(() => {
            var info = {
              'ticketCheck': `查询失败`
            };
            var formInfo = formBindingData.createFormBindingData(info);
            formProvider.updateForm(formId, formInfo);
          });
        return;
      } else {
        continue;
      }
    }
  }

  onAddForm() {
    // Called to return a FormBindingData object.
    CookieMan.getInstance(this.context).setFromCache();
    var raw = CookieMan.getInstance(this.context).get('activeTicketInfo');
    if (raw == false) {
      var obj = {
        'departTime': '',
        'trainCode': '无行程',
        'stationStr': '',
        'coachStr': `无`,
        'seatStr': `无`,
        'ticketCheck': `无`
      }
      return formBindingData.createFormBindingData(obj);
    }
    const o = JSON.parse(raw);
    for (var i = 0; i < o.tickets.length; i++) {
      const depart = (new Date(o.tickets[i].start_train_date_page)).getTime();
      var timeLeft = '';
      if (depart > new Date().getTime()) {
        const t = new Date(depart - (new Date()).getTime());
        if (t.getDate() > 1) {
          timeLeft = `${t.getDate()}天`;
        } else if (t.getHours() > 6) {
          timeLeft = `${t.getHours().toString().padStart(2, '0') + '小时'}`;
        } else {
          timeLeft = `${t.getHours() > 0 ? t.getHours().toString().padStart(2, '0') + '小时' : ''}${t.getMinutes().toString().padStart(2, '0')}分钟`;
        }
        var info = {
          'departTime': timeLeft,
          'departStation': `${o.tickets[i].stationTrainDTO.from_station_name}站`,
          'trainCode': `${o.tickets[i].stationTrainDTO.station_train_code}`,
          'stationStr': `${o.tickets[i].stationTrainDTO.to_station_name}站`,
          'coachStr': `${o.tickets[i].coach_name}车`,
          'seatStr': `${o.tickets[i].seat_name}座`,
          'ticketCheck': `点击查询`
        };
        return formBindingData.createFormBindingData(info);
      } else {
        continue;
      }
    }
  }

  onCastToNormalForm() {
    // Called when the form provider is notified that a temporary form is successfully
    // converted to a normal form.
    promptAction.showDialog({
      message: '双击卡片即可刷新'
    })
  }

  onUpdateForm(formId) {
    this.refreshForm(formId);
    // Called to notify the form provider to update a specified form.
  }

  onChangeFormVisibility() {
    // Called when the form provider receives form events from the system.
  }

  onFormEvent(formId) {
    this.refreshForm(formId);
    // Called when a specified message event defined by the form provider is triggered.
  }

  onRemoveForm() {
    // Called to notify the form provider that a specified form has been destroyed.
  }

  onAcquireFormState() {
    // Called to return a {@link FormState} object.
    return formInfo.FormState.READY;
  }
};